package com.haois.mp.database.interceptor;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.haois.mp.database.commom.enums.MpTypeEnum;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.haois.mp.database.exception.ErrorException;
import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.database.util.mp.HandleToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查
 */
@Component
public class MiniAppInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory
            .getLogger(MiniAppInterceptor.class);

    private IUserTokenService iUserTokenService;
    private WxMaService wxMaService;
    HandleToken handleToken = new HandleToken();


    public MiniAppInterceptor(IUserTokenService iUserTokenService, WxMaService wxMaService) {
        this.iUserTokenService = iUserTokenService;
        this.wxMaService = wxMaService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ErrorException, WxErrorException {
        logger.info("微信小程序登录检查开始...");
        String openId = request.getParameter("openId");
        String wxCode = request.getParameter("wxCode");
        if (StringUtils.isNotBlank(wxCode) && StringUtils.isBlank(openId)){
            WxMaJscode2SessionResult wResult = wxMaService.getUserService().getSessionInfo(wxCode);
            if (wResult != null) {
                openId = wResult.getOpenid();
            }
        }
        logger.debug("openId:" + openId);
        UserToken userToken = iUserTokenService.findByOpenId(openId, MpTypeEnum.MINIAPP.getType());
        if (userToken == null) {
            throw new ErrorException("01", "请先登录");
        }
        try {
            handleToken.analyzeJWT(userToken.getAccessToken());
        } catch (Exception e) {
            iUserTokenService.logout(userToken.getOpenId(), MpTypeEnum.MINIAPP.getType(), e.getMessage());
            throw new ErrorException("01", "请先登录");
        }
        request.setAttribute("access_token", userToken.getAccessToken());
        return true;
    }
}
